import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Goods.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class AddGoodsPage extends StatefulWidget {
  final String goodsId;

  const AddGoodsPage({Key key, this.goodsId}) : super(key: key);

  @override
  _AddGoodsPageState createState() => _AddGoodsPageState();
}

class _AddGoodsPageState extends State<AddGoodsPage> {
  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _priceController = TextEditingController();
  final TextEditingController _dataController = TextEditingController();

  ///选择图片
  List<Widget> list;
  List<File> listPics;
  var picWidth = 80.0;

  ///商品类型
  String _type = "1";

  ///加载进度
  bool _loading = false;
  String msg = "";

  ///图片地址
  String fileName;

  ///话题列表
  var _goodsTypes = ["毕设专题", "电路方案"];
  var _goodsDesc = "";

  //商品详情
  Goods _goods;

  @override
  void initState() {
    super.initState();
    picWidth = (Comm.screenWidth - 80) / 3.0;
    list = List<Widget>()..add(_buildPicButton());
    listPics = List<File>();
    _getGoods();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text(
            null != widget.goodsId ? "编辑" : "",
            style: TextStyle(fontSize: 18),
          ),
          titleSpacing: 0,
          actions: <Widget>[
            FlatButton(
                onPressed: () {
                  if (null == fileName) {
                    _uploadImage();
                  } else {
                    _submit();
                  }
                },
                child: Text(
                  '发布',
                  style: TextStyle(fontSize: 16),
                ),
                disabledTextColor: Color(0xff999999))
          ]),
      body: ProgressDialog(
        loading: _loading,
        msg: msg,
        child: SingleChildScrollView(
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _titleWidget(),
                _topicContent(),
                _addPicture(),
                SizedBox(height: 8),
                _addressWidget(),
                Container(
                    margin: EdgeInsets.only(left: 10, right: 10),
                    color: Color(0xffEEEEEE),
                    height: 1),
                _priceWidget(),
                Container(
                    margin: EdgeInsets.only(left: 10, right: 10),
                    color: Color(0xffEEEEEE),
                    height: 1),
                _typeWidget(),
                Offstage(offstage: _type != "1", child: _dataWidget()),
              ]),
        ),
      ),
    );
  }

  ///标题
  Widget _titleWidget() {
    return TextField(
      maxLines: 1,
      controller: _titleController,
      decoration: InputDecoration(
          hintText: '添加标题方便搜索~',
          hintStyle: TextStyle(color: Color(0xff999999)),
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(10)),
    );
  }

  ///内容
  Widget _topicContent() {
    return Container(
      constraints: BoxConstraints(
        maxHeight: 160,
        minHeight: 100,
        maxWidth: double.infinity,
      ),
      child: TextField(
        maxLines: null,
        controller: _contentController,
        decoration: InputDecoration(
            hintText: '商品详细描述~~',
            hintStyle: TextStyle(color: Color(0xff999999)),
            border: InputBorder.none,
            contentPadding: EdgeInsets.all(10)),
      ),
    );
  }

  ///添加图片
  Widget _addPicture() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      width: double.infinity,
      child: Wrap(
        children: null == fileName ? list : _picOldWidget(),
        spacing: 20,
        runSpacing: 20,
      ),
    );
  }

  ///选择分类
  Widget _addressWidget() {
    var type;
    if (null == _goodsDesc || _goodsDesc.isEmpty) {
      type = "选择分类";
    } else {
      type = _goodsDesc;
    }
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 6, right: 6, top: 2, bottom: 2),
        margin: EdgeInsets.only(left: 20, bottom: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: Theme.of(context).highlightColor, width: 1),
        ),
        child: Text(
          '#$type',
          style: TextStyle(color: Theme.of(context).accentColor),
        ),
      ),
      onTap: () => _showTopicTypeDialog(context),
    );
  }

  ///价格
  Widget _priceWidget() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20, top: 10),
      height: 48,
      child: TextField(
        controller: _priceController,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          prefixText: "￥",
          prefixStyle: TextStyle(fontSize: 12),
          hintText: '请输入商品价格',
          hintStyle: TextStyle(fontSize: 16, color: Color(0xff999999)),
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///类别
  Widget _typeWidget() {
    return Row(
      children: <Widget>[
        Flexible(
            child: RadioListTile<String>(
          value: "1",
          title: Text("电子资料"),
          groupValue: _type,
          onChanged: (value) {
            setState(() {
              _type = value;
            });
          },
        )),
        Flexible(
            child: RadioListTile<String>(
          value: "2",
          title: Text("实物"),
          groupValue: _type,
          onChanged: (value) {
            Toast.show("暂时只支持资料类商品发布");
          },
        )),
      ],
    );
  }

  ///选择电子资料的时候必填的资料内容
  Widget _dataWidget() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20, top: 10),
      child: TextField(
        maxLines: 4,
        controller: _dataController,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          prefixStyle: TextStyle(fontSize: 12),
          hintText: '请输入资料托管地址(推荐百度云)，付款后该信息将自动推送给买家，请确保该资料真实有效，否则将进行下架禁言处理',
          hintStyle: TextStyle(fontSize: 16, color: Color(0xff999999)),
          hintMaxLines: 3,
          border: InputBorder.none,
        ),
      ),
    );
  }

  ///选择话题类型对话框
  _showTopicTypeDialog(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("请选择分类"),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: _goodsTypes
                  .map(
                    (item) => Builder(
                      builder: (context) {
                        return RadioListTile(
                          value: item,
                          groupValue: _goodsDesc,
                          title: Text(item),
                          onChanged: (value) {
                            setState(() {
                              _goodsDesc = value;
                            });
                            Navigator.pop(context);
                          },
                        );
                      },
                    ),
                  )
                  .toList(),
            ),
          );
        });
  }

  ///构建添加图片按钮
  Widget _buildPicButton() {
    return GestureDetector(
      onTap: () {
        if (listPics.length >= 3) {
          Toast.show("最多可选3张图片");
          return;
        }
        showModalBottomSheet(
            backgroundColor: Colors.transparent,
            context: context,
            builder: (builder) {
              return _choicePic();
            });
      },
      child: Container(
        width: picWidth,
        height: picWidth,
        color: Color(0xffEEEEEE),
        child: Icon(
          Icons.add,
          color: Color(0xff999999),
        ),
      ),
    );
  }

  ///选择图片对话框
  Widget _choicePic() {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.all(10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: Column(children: <Widget>[
            FlatButton(onPressed: _openCamera, child: Text('拍照')),
            Divider(height: 1, color: Color(0xffBBBBBB)),
            FlatButton(onPressed: _openAlbum, child: Text('从相册中选择'))
          ])),
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ))
    ]);
  }

  ///打开相册
  Future _openAlbum() async {
    print('打开相册');
    Navigator.pop(context);
    AssetPicker.pickAssets(context,
            maxAssets: 3 - listPics.length,
            themeColor: Theme.of(context).accentColor)
        .then((List<AssetEntity> assets) {
      assets.forEach((AssetEntity asset) async {
        File image = await asset.file;
        listPics.add(image);
        setState(() {
          list.insert(list.length - 1, _buildPhoto(image));
        });
      });
    });
  }

  ///打开相机
  void _openCamera() async {
    Navigator.pop(context);
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    listPics.add(image);
    setState(() {
      list.insert(list.length - 1, _buildPhoto(image));
    });
  }

  ///构建图片
  Widget _buildPhoto(File image) {
    return Stack(
        overflow: Overflow.visible,
        alignment: Alignment(0.9, -0.9),
        children: <Widget>[
          Container(
            width: picWidth,
            height: picWidth,
            child: Image.file(
              image,
              width: picWidth,
              height: picWidth,
              fit: BoxFit.cover,
            ),
          ),
          GestureDetector(
            onTap: () {
              var index = listPics.indexOf(image);
              setState(() {
                listPics.removeAt(index);
                list.removeAt(index);
              });
            },
            child: Container(
              width: 18,
              height: 18,
              decoration: BoxDecoration(
                  color: Color(0x7f000000),
                  borderRadius: BorderRadius.circular(9)),
              child: Icon(Icons.clear, color: Colors.white, size: 12),
            ),
          )
        ]);
  }

  ///编辑的图片
  List<Widget> _picOldWidget() {
    if (null == fileName) {
      return [Container()];
    }
    return fileName.split(",").map((picItem) {
      return Stack(
          overflow: Overflow.visible,
          alignment: Alignment(0.9, -0.9),
          children: <Widget>[
            Container(
              width: picWidth,
              height: picWidth,
              child: CachedNetworkImage(
                imageUrl: Api.getUrl(picItem),
                fit: BoxFit.cover,
                errorWidget: (context, url, error) => CommWidget.imgError(),
              ),
            ),
            GestureDetector(
              onTap: () {
                setState(() {
                  fileName = null;
                });
              },
              child: Container(
                width: 18,
                height: 18,
                decoration: BoxDecoration(
                    color: Color(0x7f000000),
                    borderRadius: BorderRadius.circular(9)),
                child: Icon(Icons.clear, color: Colors.white, size: 12),
              ),
            )
          ]);
    }).toList();
  }

  ///上传图片
  Future _uploadImage() async {
    if (null == listPics || listPics.length <= 0) {
      Toast.show("请先选择图片");
      return;
    }
    if (_titleController.text.isEmpty) {
      Toast.show("请输入标题");
      return;
    }
    if (_contentController.text.isEmpty) {
      Toast.show("请输入详细描述");
      return;
    }
    if (_priceController.text.isEmpty) {
      Toast.show("请输入商品价格");
      return;
    }
    if (_type == "1" && _dataController.text.isEmpty) {
      Toast.show("请输入资料托管地址");
      return;
    }
    if (null == _goodsDesc || _goodsDesc.isEmpty) {
      Toast.show("请选择分类");
      return;
    }
    setState(() {
      _loading = true;
      msg = "图片上传中...";
    });
    Http.upload(Api.URL_UPLOADS, listPics, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      print("上传结果：" + data);
      fileName = "";
      jsonDecode(data).forEach((item) {
        fileName = "$fileName${item["path"]},";
      });
      if (fileName.endsWith(",")) {
        fileName = fileName.substring(0, fileName.length - 1);
      }
      _submit();
    }, errorCallBack: (errorMsg) {
      setState(() {
        _loading = false;
      });
    });
  }

  ///获取商品详情
  void _getGoods() async {
    if (null == widget.goodsId) {
      return;
    }
    String url = "${Api.URL_GOODSINFO}?goodsId=${widget.goodsId}";
    Http.get(url, successCallBack: (data) {
      setState(() {
        _goods = Goods.fromJson(json.decode(data));
        _titleController.text = _goods.goodsName;
        _contentController.text = _goods.goodsInfo;
        _priceController.text = "${_goods.price}";
        _dataController.text = _goods.dataLink;
        _goodsDesc = _goods.classtify;
        fileName = _goods.goodsImg;
        _type = _goods.type;
      });
    });
  }

  ///发布商品
  void _submit() {
    if (_loading) return;
    setState(() {
      msg = "发布中...";
      _loading = true;
    });
    String title = _titleController.text;
    String content = _contentController.text;
    String price = _priceController.text;
    String data = _dataController.text;
    Map<String, String> map = Map();
    if (null != _goods) {
      map["goodsId"] = _goods.goodsId;
    }
    map["goodsName"] = title;
    map["goodsInfo"] = content;
    map["goodsImg"] = fileName;
    map["price"] = price;
    map["type"] = _type;
    map["classtify"] = _goodsDesc;
    map["dataLink"] = data;
    map["address"] = Comm.city;
    Http.post(Api.URL_GOODSADD, params: map, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      Toast.show('发布成功');
      Navigator.of(context).pop();
    }, errorCallBack: (msg) {
      Toast.show(msg);
      setState(() {
        _loading = false;
      });
    });
  }
}
